#!/bin/bash
packages_path=$1
batch_count=$2
tar_path=${packages_path}/../compress_rpm

function check(){
    if [ ! -d ${packages_path} ];then
        echo "${packages_path} is not exist"
        exit 1
    fi
    
    if [ -d ${tar_path} ];then
        read -p "[WARRNING]${tar_path} is existed,please remove it y/n: " rm_tar_path
        if [ ${rm_tar_path} == 'y' ];then
            rm -rf ${tar_path}
        else
            exit 1
        fi        
    else
        mkdir -p ${tar_path}
    fi     
} 

function unzip_file(){
    tar_path=$(readlink -f ${tar_path})
    cd ${packages_path}
    packages_list=($(ls *.rpm))
    packages_num=${#packages_list[@]}

    start_index=0
    tar_index=0
    while [ $(expr $start_index + $batch_count) -lt ${packages_num} ]; do
        tar -cf ${tar_path}/package${tar_index}.tar ${packages_list[@]:${start_index}:${batch_count}}
        start_index=$(expr $start_index + $batch_count)
        tar_index=$(expr ${tar_index} + 1)
    done

    tar -cf ${tar_path}/package${tar_index}.tar ${packages_list[@]:${start_index}:${batch_count}}
    
    
    echo "The package is compressed in batches. The package is stored in ${tar_path}."
    exit 0
}

check
unzip_file




